package com.promise.jokerdream.work.signin.before

import com.promise.jokerdream.manager.ExecutionHistoryManager
import com.promise.jokerdream.repository.GameApi
import com.promise.jokerdream.repository.foldWithApiException
import com.promise.jokerdream.response.pc.QueryLoginGiftResponse
import com.promise.jokerdream.utils.AppContext
import com.promise.jokerdream.work.BaseWork
import com.promise.jokerdream.work.WorkResult

// 登录有礼工作
class LoginGiftWork(override val uin: String): BaseWork(uin) {

    private val gameApi = GameApi.Companion.getInstance()
    private val historyManager by lazy { ExecutionHistoryManager.Companion.getInstance(AppContext.get()) }

    override val name: String
        get() = "登录有礼"

    override val isActWork: Boolean
        get() = true

    override suspend fun executeWork(): WorkResult {
        return try {
            // 查询登录有礼信息
            val queryResult = gameApi.queryLoginGift()
            queryResult.foldWithApiException(
                onSuccess = { response ->
                    processLoginGift(response)
                },
                onFailure = { code, msg ->
                    historyManager.addHistory(name, msg, code)
                    WorkResult.Failure(Exception(msg), msg)
                }
            )
        } catch (e: Exception) {
            historyManager.addHistory(name, e.message)
            WorkResult.Failure(e, e.message)
        }
    }

    /**
     * 处理登录有礼逻辑
     */
    private suspend fun processLoginGift(response: QueryLoginGiftResponse): WorkResult {
        // 找到free中第一个status为1的index
        val freeIndex = response.free.indexOfFirst { it == 1 }
        if (freeIndex != -1) {
            // 领取免费奖励
            val claimResult = gameApi.claimLoginGift(1, freeIndex) // 1为免费
            return claimResult.foldWithApiException(
                onSuccess = { claimResponse ->
                    historyManager.addHistory(name, claimResponse.getDescription())
                    WorkResult.Success
                },
                onFailure = { code, msg ->
                    historyManager.addHistory(name, msg, code)
                    WorkResult.Failure(Exception(msg), msg)
                }
            )
        }
        
        // 找到pay中第一个status为1的index
        val payIndex = response.pay.indexOfFirst { it == 1 }
        if (payIndex != -1) {
            // 领取付费奖励
            val claimResult = gameApi.claimLoginGift(2, payIndex) // 2为付费
            return claimResult.foldWithApiException(
                onSuccess = { claimResponse ->
                    historyManager.addHistory(name, claimResponse.getDescription())
                    WorkResult.Success
                },
                onFailure = { code, msg ->
                    historyManager.addHistory(name, msg, code)
                    WorkResult.Failure(Exception(msg), msg)
                }
            )
        }
        
        // 没有找到可领取的奖励
        return WorkResult.Success
    }
}